<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import * as echarts from 'echarts';
require('echarts/theme/macarons2') // echarts theme
import resize from './mixins/resize'
import { listAge } from '@/api/system/resumeStatistics.js'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '350px'
    }
  },
  data() {
    return {
      chart: null,
      barYValue: [],
      barXValue: []
    }
  },
  mounted() {
    this.$nextTick(() => {
      listAge().then(res => {
        for (let i = 0; i < res.data.name.length; i++) {
          res.data.name[i] = `${res.data.name[i]}岁`
        }

        this.barXValue = res.data.name
        res.data.name.forEach((el, idx) => {
          let obj = {
            name: el,
            value: res.data.value[idx]
          }
          this.barYValue.push(obj)
        })
        this.initChart()
      })
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons2')

      this.chart.setOption({
        title: {
          text: "年龄分布",
          x: "center",
          textStyle: {
            color: "#595959",
            fontSize: 22,
          },
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          left: 'center',
          bottom: '10',
          data: this.barXValue
        },
        series: [
          {
            name: '年龄分布',
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '50%'],
            data: this.barYValue,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
